package jxml.explorer;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import jxml.editeur.EditeurConfig;
import jxml.editeur.TitrePan;
import jxml.main.Main;
import jxml.menu.CreateProject;
import jxml.utils.Jdom;

class FSTransfer extends TransferHandler {
	  public boolean importData(JComponent comp, Transferable t) {
	    if (!(comp instanceof JTree)) {
	      return false;
	    }
	    if (!t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
	      return false;
	    }
	    JTree tree = (JTree) comp;
	    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
	    try {
	      List data = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
	      Iterator i = data.iterator();
	      while (i.hasNext()) {
	        File f = (File) i.next();
	        //root.add(new DefaultMutableTreeNode(f.getName()));


	        JTree.DropLocation dl =
	                (JTree.DropLocation)tree.getDropLocation();
	        
	        TreePath dest = dl.getPath();
	        String full = dest.toString().replaceAll( "]", "" ).replaceAll( "\\[", "" ).replaceAll( ",", "/" ).replaceAll( " ", "" ).replaceAll( "/Default", "" ).replaceAll( "/xmlsrc", "" );
	        String nows = full.substring(full.indexOf("/")+1, full.length());
	        String project = nows;
	        if(nows.contains("/")){
	         project = nows.substring(0, nows.indexOf("/"));
	        }
	        
	        String destfolder = project+"/src";
	        if(f.getName().endsWith(".xml")){
	        	 destfolder = project+"/bin/xml";
	        }
	        
	        if(f.getName().endsWith(".java")){
	        	if(nows.endsWith(".java")){
	        		destfolder = project+"/"+nows.substring(nows.indexOf("/")+1,nows.lastIndexOf("/"));
	        	}
	        	
	        	else if (nows.contains("/") && !nows.endsWith(".xml")){
	        		destfolder=nows;
	        	}
	        	else{
	        		destfolder = project+"/src";
	        	}
	        	
	        }
	        
	        
	        //Copying file to folder 
	        
	        if(!new File(Explorer.WORKSPACE + "/"
					+  destfolder + "/"+f.getName()).exists()){
	        InputStream is = null;
			OutputStream os = null;
			try {

				is = new FileInputStream(f.getPath());

				os = new FileOutputStream(new File(Explorer.WORKSPACE + "/"
						+  destfolder + "/"+f.getName()));
				int read = 0;
				byte[] bytes = new byte[1024];
				while ((read = is.read(bytes)) != -1) {
					os.write(bytes, 0, read);
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (os != null) {
					try {
						// outputStream.flush();
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}

				}

			}
	        
	        
	        //Add in Build , In Tab , Refresh
			if(f.getName().endsWith(".xml")){
				
			Jdom.CreateXml( project, "xmlsrc", f.getName(), 0 );
			
			CreateXml.addEditToDock( f.getName(),2, destfolder+"/"+f.getName());
			
			Explorer.rafrechir();
			
			TitrePan.SaveAct( (TitrePan) EditeurConfig.getTabbedpane().getTabComponentAt(
	                TitrePan.returnTabNbr(  destfolder + "/"+f.getName() ) ) );
			
			}
			
			if(f.getName().endsWith(".java")){
				
				CreateClass.addEditToDock( f.getName(), 2, destfolder+"/"+f.getName());
				
				if(destfolder.equals(project+"/src")){
					Jdom.CreateClass( project, "src", f.getName(), 0 );
				}
				else{
					Jdom.CreateClass( project, destfolder.replace(project+"/src/", "").replace("/", "."),f.getName(), 1 );
				}
								
				
				Explorer.rafrechir();
				
				TitrePan.SaveAct( (TitrePan) EditeurConfig.getTabbedpane().getTabComponentAt(
		                TitrePan.returnTabNbr(  destfolder + "/"+f.getName() ) ) );
				
			}
	        
	        // Configure for drop mode.
	        
	        }
	        else{
	        	JOptionPane.showMessageDialog( Main.getInstance(),"File "+f.getName()+" already exists in "+
	        			destfolder+" !" );
	        }
	        
	      }
	      model.reload();
	      return true;
	    } catch (Exception ioe) {
	      System.out.println(ioe);
	    }
	    return false;
	  }

	  public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
	    if (comp instanceof JTree) {
	      for (int i = 0; i < transferFlavors.length; i++) {
	        if (!transferFlavors[i].equals(DataFlavor.javaFileListFlavor)) {
	          return false;
	        }
	      }
	      return true;
	    }
	    return false;
	  }
	}